#!/bin/bash
#
# Copyright (c) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy of
# the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations under
# the License.

# copied from:
# http://code.google.com/p/oacurl/source/browse/oacurl

function resolve_symlink {
  SCRIPT=$1 NEWSCRIPT=''

  until [ "$SCRIPT" = "$NEWSCRIPT" ]; do
    if [ "${SCRIPT:0:1}" = '.' ]; then
      SCRIPT=$PWD/$SCRIPT;
    fi

    cd $(dirname $SCRIPT)

    if [ ! "${SCRIPT:0:1}" = '.' ]; then
      SCRIPT=$(basename $SCRIPT);
    fi

    SCRIPT=${NEWSCRIPT:=$SCRIPT}
    NEWSCRIPT=$(ls -l $SCRIPT | awk '{ print $NF }')
  done

  if [ ! "${SCRIPT:0:1}" = '/' ]; then
    SCRIPT=$PWD/$SCRIPT;
  fi

  echo $(dirname $SCRIPT)
}

DISCOVERY_HOME=$(resolve_symlink $0)

# set JAVACMD
if [ -z "$JAVACMD" ] ; then
  if [ -n "$JAVA_HOME"  ] ; then
    JAVACMD=$JAVA_HOME/bin/java
  else
    JAVACMD=`which java`
  fi
fi

if [ ! -x "$JAVACMD" ] ; then
  echo "Error: JAVA_HOME is not defined correctly."
  echo "  We cannot execute $JAVACMD"
  exit
fi

# run command
args=($@);

$JAVACMD -jar $DISCOVERY_HOME/target/discovery-sample-1.1.0-jar-with-dependencies.jar $@